﻿using System;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Channels;
using System.ServiceModel.Configuration;
using System.ServiceModel.Description;

namespace SBPweb.PROvibe.Server.Framework.Communication
{

    public class PollingDuplexServiceHostFactory<TContract, TService> : ServiceHostFactoryBase
    {
        public override ServiceHostBase CreateServiceHost(string constructorString,
            Uri[] baseAddresses)
        {
            return new PollingDuplexServiceHost<TContract, TService>(baseAddresses);
        }
    }

    public class PollingDuplexServiceHost<TContract, TService> : ServiceHost
    {

        public PollingDuplexServiceHost(params System.Uri[] addresses)
        {
            base.InitializeDescription(typeof(TService), new UriSchemeKeyedCollection(addresses));
        }

        public event EventHandler<ChannelEventArgs> ChannelOpened;

        protected override void InitializeRuntime()
        {
            // Define the binding and set time-outs
            PollingDuplexBindingElement bindingElement = new PollingDuplexBindingElement()
            {
                ServerPollTimeout = TimeSpan.FromMinutes(1),
                InactivityTimeout = TimeSpan.FromMinutes(2)
            };

            ServiceEndpoint sep =
            // Add an endpoint for the given service contract
            this.AddServiceEndpoint(
                typeof(TContract),
                new CustomBinding(
                    bindingElement,
                    new TextMessageEncodingBindingElement(
                        MessageVersion.Soap11,
                        System.Text.Encoding.UTF8),
                    new HttpTransportBindingElement()),
                "");

            base.InitializeRuntime();
        }

        internal void OnChannelOpened(ServerChannel channel)
        {
            if (ChannelOpened != null)
            {
                ChannelOpened(this, new ChannelEventArgs(channel));
            }
        }

    }

}